<template>
  <div class="map-container">
    <div ref="map" class="map"></div>
    <ul class="topMenu">
      <li class="tips">
        <i class="iconfont">&#xe65b;</i>
        {{this.$store.getters.area}}
      </li>
      <li v-if="this.$store.getters.backable" class="tips goBack" @click="goBack">
        <i class="iconfont">&#xe65b;</i>返回上一级
      </li>
    </ul>
  </div>
</template>
<script>
import { mapGetters, mapState } from 'vuex'
const AREA_COLORS = [
  '#2388f8',
  '#177ef0',
  '#2387f4',
  '#3690f3',
  '#4b9df6',
  '#318ff6',
  '#1e88fd',
  '#1480f6',
  '#107cf2',
  '#2186f4',
  '#1a81f1',
  '#0f76e8',
  '#1f80ea',
  '#1276e4'
]

export default {
  name: 'Map',
  props: {
    loading: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      option: {
        geo: {
          roam: false,
          nameMap: {
            china: '中国'
          },
          label: {
            normal: {
              show: true,
              textStyle: {
                color: '#fff',
                fontSize: 13
              }
            },
            emphasis: {
              show: true,
              textStyle: {
                color: '#fff',
                fontSize: 13
              }
            }
          },
          itemStyle: {
            normal: {
              areaColor: '#1683fb',
              borderColor: '#47e3ff',
              borderType: 'solid',
              borderWidth: 0.4
            },
            emphasis: {
              areaColor: '#1da8fc'
            }
          }
        },
        tooltip: {
          trigger: 'item',
          backgroundColor: 'transparent',
          formatter: params => {
            if (params.seriesName !== '体温报警区域') {
              return this.renderTip(
                params.data.name,
                this.tagInfo.filter(i =>
                  this.$common.featureMatch(params.data, i)
                )[0]
              )
            }
          }
        },
        legend: {
          data: ['体温报警区域', '所有园所分布'],
          orient: 'vertical',
          left: '20',
          bottom: '20',
          textStyle: {
            color: '#4dd5ff'
          }
        },
        animationDuration: 1000,
        animationEasing: 'cubicOut',
        animationDurationUpdate: 1000
      },
      mapChart: null
    }
  },
  computed: {
    ...mapState({
      mapArea: 'mapArea',
      warnPercent: 'warnPercent'
    }),
    ...mapGetters({
      gardenFeatures: 'gardenFeatures',
      attendWarnFeatures: 'attendWarnFeatures',
      tagInfo: 'tagInfo'
    })
  },
  watch: {
    attendWarnFeatures: {
      // 报警
      handler () {
        if (this.option.series && this.option.series[1]) {
          this.option.series[1].data = this.attendWarnFeatures
          this.mapChart.setOption(this.option)
        }
      }
    }
  },
  methods: {
    // 返回上级地图
    goBack () {
      this.$store.commit('popCrumb')
      this.initFeature()
    },
    async mapEchartsInit () {
      await this.$store.dispatch('fetchCityMap')
      await this.$store.dispatch('fetchAreaIdList')
      await this.$store.dispatch('fetchProvinces')

      // 绘制地图
      this.mapChart = this.$echarts.init(this.$refs.map)

      // 地图点击事件
      this.mapChart.on('click', this.handleMapClick)

      await this.initFeature()
    },
    async initFeature () {
      this.$emit('update:loading', true)
      await this.$store.dispatch('fetchMapFeatures')
      this.drawMap()
      this.$emit('update:loading', false)
    },
    drawMap () {
      // 注册地图
      this.$echarts.registerMap(this.mapArea.name, this.mapArea.features)
      // 绘制地图
      this.renderMap()
    },
    handleMapClick (params) {
      const area = this.$store.getters.areas.filter(a =>
        this.$common.featureMatch(params.data || params, a)
      )[0]
      this.$store.commit('pushCrumb', {
        id: area.id,
        name: area.name,
        level: this.$store.getters.subAreaLevel
      })

      if (params.seriesName === '所有园所分布') {
        // 切换到园所视角
        this.$router.push({path: '/garden' + this.$route.path})
      } else {
        this.initFeature()
      }
    },
    renderMap () {
      this.option.geo.map = this.mapArea.name
      this.option.geo.regions = this.$common
        .getPair(this.$store.getters.featureNames, AREA_COLORS)
        .map(([name, areaColor]) => ({
          name,
          itemStyle: {
            areaColor
          }
        }))

      if (this.mapArea.level !== '区级') {
        this.option.series = [{
          name: '所有中心区域',
          type: 'effectScatter',
          coordinateSystem: 'geo',
          data: this.$store.getters.featurePairs,
          symbolSize: 8,
          symbol: '',
          color: '#0060ca',
          showEffectOn: 'render',
          rippleEffect: {
            brushType: 'stroke'
          },
          hoverAnimation: true
        }]
      } else {
        this.option.series = [{
          name: '所有园所分布',
          type: 'scatter',
          coordinateSystem: 'geo',
          data: this.gardenFeatures,
          symbolSize: 18,
          symbol:
            'path://M849.6 812V486.2l-300-150V137L174.6 324.6V812H137v75h750V812h-37.4z m-450-37.4h-75v-75h75v75z m0-150h-75v-75h75v75z m0-150h-75v-75h75v75z m300 300h-75v-75h75v75z m0-150h-75v-75h75v75z',
          color: '#92f5ff'
        }]
      }
      if (this.$route.name === 'HealthyToday') {
        this.option.series.push({
          name: '体温报警区域',
          type: 'effectScatter',
          coordinateSystem: 'geo',
          silent: true,
          zlevel: 9,
          data: [],
          symbolSize: 18,
          symbol:
            'path://m291.2229,189.35269l-5.03619,-8.72086c-1.51839,-2.62844 -4.00193,-6.93142 -5.52033,-9.56037l-5.03572,-8.72033c-1.5199,-2.62999 -4.00344,-2.62999 -5.52133,0l-5.0347,8.72033c-1.51839,2.62895 -4.00345,6.93293 -5.52134,9.56037l-5.03521,8.72086c-1.51839,2.63098 -0.2756,4.78145 2.76067,4.78145l31.18046,0c3.03931,0 4.28056,-2.15047 2.76368,-4.78145l0,0zm-16.91486,1.35006l-2.98695,0l0,-2.86743l2.98695,0l0,2.86743zm-0.1439,-4.98027l-2.69659,0l-0.26799,-12.26868l3.20865,0l-0.24407,12.26868l0,0z',
          color: '#ffe98f',
          showEffectOn: 'render',
          rippleEffect: {
            brushType: 'stroke'
          },
          hoverAnimation: true
        })
      }
      // 渲染地图
      this.mapChart.setOption(this.option)
    },
    renderTip (name, res) {
      const { mapTag, warnPercent } = this.$store.state
      if (res) {
        let html = '<div class="tag-box">'
        html += '<h3><i class="iconfont">&#xe79a</i>' + name + '</h3>'
        html += '<ul>'
        switch (mapTag) {
          case '健康安全':
            html += '<li>出勤人数<i>' + res.attendCount + '人</i></li>'
            html += '<li>体温异常人数<i>' + res.warnCount + '人</i></li>'
            html += '<li>需要服药人数<i>' + res.fyCount + '人</i></li>'
            html += '<li>需要加餐人数<i>' + res.jcCount + '人</i></li>'
            html += '<li>需要观察人数<i>' + res.gcCount + '人</i></li>'
            if (
              (res.leaveCount / res.totalCount) * 100 >= warnPercent.attend ||
              ((res.gcCount + res.fyCount) / res.totalCount) * 100 >=
                warnPercent.sick
            ) {
              html +=
                '<li class="warn">请假预警<i>' +
                ((res.leaveCount / res.totalCount) * 100).toFixed(2) +
                '%</i></li>'
              html +=
                '<li class="warn">疾病预警<i>' +
                (((res.gcCount + res.fyCount) / res.totalCount) * 100).toFixed(
                  2
                ) +
                '%</i></li>'
            } else {
              html += '<li style="color:#62ff15">请假预警<i>暂无预警</i></li>'
              html += '<li style="color:#62ff15">疾病预警<i>暂无预警</i></li>'
            }
            break
          case '身体发育':
            html += `<li>BMI偏轻<i>${res['偏胖']}人</i></li>`
            html += `<li>BMI均值<i>${res['偏轻']}人</i></li>`
            html += `<li>BMI肥胖<i>${res['正常']}人</i></li>`
            html += `<li>BMI偏重<i>${res['肥胖']}人</i></li>`
            break
          case '睡眠/体育活动':
            html += '<li>强度低<i>' + res.percentLowery + '%</i></li>'
            html += '<li>强度中<i>' + res.percentCenter + '%</i></li>'
            html += '<li>强度高<i>' + res.percentHeavy + '%</i></li>'
            html += '<li>基本没睡<i>' + res.percentNoSleep + '%</i></li>'
            html += '<li>睡眠较少<i>' + res.percentLessSleep + '%</i></li>'
            html += '<li>睡眠正常<i>' + res.percentNormalSleep + '%</i></li>'
            html += '<li>睡眠正常<i>' + res.percentMoreSleep + '%</i></li>'
            break
        }
        html += '</ul>'
        html += '</div>'
        return html
      } else {
        return (
          '<div class="tag-box"><h3><i class="iconfont">&#xe60d;</i>' +
          name +
          '</h3><p style="color:#ffe98f">暂无数据</p></div>'
        )
      }
    },
    onResize () {
      this.mapChart.resize()
    }
  },
  async mounted () {
    // 加载地图
    await this.mapEchartsInit()

    this.onResizeHandle = this._.debounce(this.onResize, 200)
    window.addEventListener('resize', this.onResizeHandle)
  },
  beforeDestroy () {
    window.removeEventListener('resize', this.onResizeHandle)
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl';
@import '~styles/mixins.styl';

.map-container {
  position: relative;
  width: 100%;
  height: 100%;

  .topMenu {
    position: absolute;
    z-index: 9;
    top: 10px;
    left: 0;

    li {
      float: left;
      margin-left: 10px;
    }

    li.goBack {
      cursor: pointer;
    }
  }

  .upLevelBtn {
    left: 100px;
    background: none;
    color: #b0d0f1;
    cursor: pointer;
  }

  .map {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }
}
</style>
<style>
.tag-box {
  position: relative;
  background: rgba(9, 26, 79, 0.7);
  padding: 20px;
  box-shadow: 0 0 30px rgba(69, 120, 192, 0.6) inset;
}
.tag-box:before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 20px;
  box-sizing: border-box;
  border: solid #1e82c7;
  border-width: 1px 1px 0 1px;
}
.tag-box:after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 20px;
  box-sizing: border-box;
  border: solid #1e82c7;
  border-width: 0 1px 1px 1px;
}
.tag-box h3 i {
  margin-right: 5px;
}
.tag-box li {
  width: 160px;
  color: #40b7e6;
  padding-top: 10px;
}
.tag-box li.warn {
  color: #ffe98f;
}
.tag-box li i {
  float: right;
}
</style>
